package org.groupg.project.configmanager.ui;

import org.groupg.project.configmanager.model.DatabaseConfig;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 数据库配置对话框 - 用于添加和编辑数据库配置
 */
public class DatabaseConfigDialog extends JDialog {
    private DatabaseConfig config;
    private boolean saved = false;

    // 表单字段
    private JTextField nameField;
    private JComboBox<String> driverComboBox;
    private JTextField urlField;
    private JTextField usernameField;
    private JTextField passwordField;

    // 按钮
    private JButton saveButton;
    private JButton cancelButton;
    private JButton testButton;
    private JButton generateUrlButton;

    // 常用数据库驱动和URL模板
    private static final String[][] DATABASE_TYPES = {
        {"MySQL", "com.mysql.cj.jdbc.Driver", "jdbc:mysql://localhost:3306/database_name"},
        {"PostgreSQL", "org.postgresql.Driver", "jdbc:postgresql://localhost:5432/database_name"},
        {"Oracle", "oracle.jdbc.OracleDriver", "jdbc:oracle:thin:@localhost:1521:xe"},
        {"SQL Server", "com.microsoft.sqlserver.jdbc.SQLServerDriver", "jdbc:sqlserver://localhost:1433;databaseName=database_name"},
        {"H2 (Embedded)", "org.h2.Driver", "jdbc:h2:file:./data/database_name"},
        {"H2 (Memory)", "org.h2.Driver", "jdbc:h2:mem:database_name"}
    };

    /**
     * 构造函数
     * @param owner 父窗口
     * @param config 数据库配置对象，如果为null则创建新配置
     */
    public DatabaseConfigDialog(Frame owner, DatabaseConfig config) {
        super(owner, config == null ? "添加数据库配置" : "编辑数据库配置", true);
        this.config = config != null ? config : new DatabaseConfig();
        initializeUI();
        populateFields();
    }

    /**
     * 初始化用户界面
     */
    private void initializeUI() {
        setLayout(new BorderLayout(10, 10));
        setSize(600, 400);
        setLocationRelativeTo(getOwner());
        setResizable(true);

        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 表单面板
        JPanel formPanel = new JPanel(new GridLayout(5, 2, 5, 10));

        // 名称字段
        formPanel.add(new JLabel("名称*:"));
        nameField = new JTextField();
        formPanel.add(nameField);

        // 驱动类
        formPanel.add(new JLabel("驱动类*:"));
        driverComboBox = new JComboBox<>();
        for (String[] dbType : DATABASE_TYPES) {
            driverComboBox.addItem(dbType[0]);
        }
        driverComboBox.setEditable(true); // 允许自定义驱动类
        formPanel.add(driverComboBox);

        // 连接URL
        formPanel.add(new JLabel("连接URL*:"));
        JPanel urlPanel = new JPanel(new BorderLayout(5, 0));
        urlField = new JTextField();
        generateUrlButton = new JButton("生成");
        generateUrlButton.setMargin(new Insets(2, 5, 2, 5));
        urlPanel.add(urlField, BorderLayout.CENTER);
        urlPanel.add(generateUrlButton, BorderLayout.EAST);
        formPanel.add(urlPanel);

        // 用户名
        formPanel.add(new JLabel("用户名*:"));
        usernameField = new JTextField();
        formPanel.add(usernameField);

        // 密码
        formPanel.add(new JLabel("密码:"));
        passwordField = new JTextField();
        formPanel.add(passwordField);

        // 添加表单面板到主面板
        mainPanel.add(formPanel, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        testButton = new JButton("测试连接");
        saveButton = new JButton("保存");
        cancelButton = new JButton("取消");

        // 设置按钮快捷键
        saveButton.setMnemonic('S');
        cancelButton.setMnemonic('C');
        testButton.setMnemonic('T');

        buttonPanel.add(testButton);
        buttonPanel.add(Box.createHorizontalStrut(10));
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);

        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        add(mainPanel, BorderLayout.CENTER);

        // 添加事件监听器
        setupEventListeners();

        // 设置默认按钮
        getRootPane().setDefaultButton(saveButton);
    }

    /**
     * 设置事件监听器
     */
    private void setupEventListeners() {
        saveButton.addActionListener(e -> saveConfig());
        cancelButton.addActionListener(e -> dispose());
        testButton.addActionListener(e -> testConnection());
        generateUrlButton.addActionListener(e -> generateUrl());

        // 数据库类型改变时更新驱动和URL模板
        driverComboBox.addActionListener(e -> updateDriverAndUrl());
    }

    /**
     * 根据选择的数据库类型更新驱动类和URL
     */
    private void updateDriverAndUrl() {
        String selectedDb = (String) driverComboBox.getSelectedItem();
        for (String[] dbType : DATABASE_TYPES) {
            if (dbType[0].equals(selectedDb)) {
                // 只有当用户没有自定义URL时才自动更新
                if (urlField.getText().isEmpty() || isGeneratedUrl(urlField.getText())) {
                    urlField.setText(dbType[2]);
                }
                break;
            }
        }
    }

    /**
     * 检查URL是否为生成的模板URL
     */
    private boolean isGeneratedUrl(String url) {
        for (String[] dbType : DATABASE_TYPES) {
            if (url.equals(dbType[2]) || url.contains("database_name")) {
                return true;
            }
        }
        return false;
    }

    /**
     * 生成URL模板
     */
    private void generateUrl() {
        String selectedDb = (String) driverComboBox.getSelectedItem();
        for (String[] dbType : DATABASE_TYPES) {
            if (dbType[0].equals(selectedDb)) {
                urlField.setText(dbType[2]);
                break;
            }
        }
    }

    /**
     * 用配置数据填充表单字段
     */
    private void populateFields() {
        if (config.getId() != null) {
            nameField.setText(config.getName() != null ? config.getName() : "");

            // 设置驱动类
            String driverClass = config.getDriverClass();
            boolean found = false;
            if (driverClass != null) {
                for (String[] dbType : DATABASE_TYPES) {
                    if (dbType[1].equals(driverClass)) {
                        driverComboBox.setSelectedItem(dbType[0]);
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    driverComboBox.setSelectedItem(driverClass); // 自定义驱动类
                }
            }

            urlField.setText(config.getUrl() != null ? config.getUrl() : "");
            usernameField.setText(config.getUsername() != null ? config.getUsername() : "");
            passwordField.setText(config.getPassword() != null ? config.getPassword() : "");
        } else {
            // 新配置，设置默认值
            driverComboBox.setSelectedIndex(0); // 默认选择MySQL
            updateDriverAndUrl();
        }
    }

    /**
     * 保存配置
     */
    private void saveConfig() {
        // 验证必填字段
        if (nameField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入配置名称", "错误", JOptionPane.ERROR_MESSAGE);
            nameField.requestFocus();
            return;
        }

        if (urlField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入连接URL", "错误", JOptionPane.ERROR_MESSAGE);
            urlField.requestFocus();
            return;
        }

        if (usernameField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入用户名", "错误", JOptionPane.ERROR_MESSAGE);
            usernameField.requestFocus();
            return;
        }

        // 获取驱动类
        String driverClass = "";
        String selectedDb = (String) driverComboBox.getSelectedItem();
        boolean found = false;
        for (String[] dbType : DATABASE_TYPES) {
            if (dbType[0].equals(selectedDb)) {
                driverClass = dbType[1];
                found = true;
                break;
            }
        }
        if (!found) {
            driverClass = selectedDb; // 自定义驱动类
        }

        // 更新配置对象
        config.setName(nameField.getText().trim());
        config.setDriverClass(driverClass);
        config.setUrl(urlField.getText().trim());
        config.setUsername(usernameField.getText().trim());
        config.setPassword(new String(passwordField.getText().trim()));

        // 标记为已保存并关闭对话框
        saved = true;
        dispose();
    }

    /**
     * 测试数据库连接
     */
    private void testConnection() {
        // 基本验证
        if (urlField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入连接URL", "错误", JOptionPane.ERROR_MESSAGE);
            urlField.requestFocus();
            return;
        }

        if (usernameField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入用户名", "错误", JOptionPane.ERROR_MESSAGE);
            usernameField.requestFocus();
            return;
        }

        // 显示连接信息
        String testInfo = String.format(
            "数据库连接测试信息:\n\n" +
            "驱动类: %s\n" +
            "URL: %s\n" +
            "用户名: %s\n\n" +
            "注意: 实际连接测试功能需要加载对应数据库驱动",
            getDriverClass(),
            urlField.getText().trim(),
            usernameField.getText().trim()
        );

        JOptionPane.showMessageDialog(this, testInfo, "数据库连接测试", JOptionPane.INFORMATION_MESSAGE);
    }

    /**
     * 获取驱动类名称
     */
    private String getDriverClass() {
        String selectedDb = (String) driverComboBox.getSelectedItem();
        for (String[] dbType : DATABASE_TYPES) {
            if (dbType[0].equals(selectedDb)) {
                return dbType[1];
            }
        }
        return selectedDb; // 自定义驱动类
    }

    /**
     * 检查配置是否已保存
     * @return 如果已保存返回true，否则返回false
     */
    public boolean isSaved() {
        return saved;
    }

    /**
     * 获取配置对象
     * @return 配置对象
     */
    public DatabaseConfig getConfig() {
        return config;
    }
}